﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MovieRental_Presentation.Helpers;
using MovieRental_Presentation.DataViews;
using MovieRental.EnhancedEntities;
using MovieRental.Entities;
using MovieRental_Presentation.Validation;
using MovieRental.BuisnessComponents.Exceptions;


namespace MovieRental_Presentation
{
	public partial class MovieDetails
	{
        private MovieDetailsDataView _dataView;

		public MovieDetails(Movie movie, bool readOnly = true)
		{
			this.InitializeComponent();
            _dataView = new MovieDetailsDataView(movie.Entity.Id);
            DataContext = _dataView;
            _dataView.IsReadOnly = readOnly;
            mediaTypesComboBox.DataContext = _dataView;

            (Application.Current as App).WebPageNotFoundExceptionHandler += OnPageNotFound;
		}

        private void OnPageNotFound(object sender, EventArgs args)
        {
            webPageFrame.Source = new Uri("WebPageNotFound.xaml", UriKind.Relative);
            loadingGrid.Visibility = Visibility.Hidden;
        }

        private void SetBindingForQuantityTextBox()
        {
            Binding binding = new Binding("Quantity");
            var rule = new QuantityValidationRule();
            EditionInfo edition = (EditionInfo)quantityTextBox.DataContext;
            rule.EditionId = edition.Id;
            rule.ValidatesOnTargetUpdated = true;
            rule.ValidationStep = ValidationStep.ConvertedProposedValue;
            binding.ValidationRules.Add(rule);
            quantityTextBox.SetBinding(TextBox.TextProperty, binding);
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            editionGrid.Visibility = Visibility.Visible;
            manageEditionPanel.Visibility = Visibility.Collapsed;
            EditionInfo defaultEdition = new EditionInfo();
            defaultEdition.Quantity = 1;
            defaultEdition.PricePerDay = 3.0;
            _dataView.SelectedEdition = new Edition(defaultEdition);
            mediaTypesComboBox.SelectedIndex = 0;
            SetBindingForQuantityTextBox();
            applyEditionChangesButton.Content = "Add";
        }

        private void mediaTypesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var component = ComponentManager.Instance.MediaTypeComponent;
            _dataView.SelectedEdition.Entity.MediaTypeId = component.GetMediaTypeByName((string)mediaTypesComboBox.SelectedItem).Id;
        }

        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            var globalResources = (Application.Current as App).Resources;
            Edition edition = _dataView.SelectedEdition;
            if (!ComponentManager.Instance.EditionComponent.CanDelete(edition.Entity))
            {
                string message = string.Format((string) globalResources["deleteEditionFailedMessage"], edition.Entity.Quantity - edition.InStockQuantity);
                MessageBox.Show(message, "Can't delete the edition.", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
                ComponentManager.Instance.EditionComponent.Delete(_dataView.SelectedEdition.Entity);
        }

        private void backButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void editMovieButton_Click(object sender, RoutedEventArgs e)
        {
            _dataView.IsReadOnly = false;
        }

        private void manageDiscountButton_Click(object sender, RoutedEventArgs e)
        {
            manageDiscountGrid.Visibility = Visibility.Visible;
            manageEditionPanel.Visibility = Visibility.Collapsed;
        }

        private void editEditionButton_Click(object sender, RoutedEventArgs e)
        {
            var mediaComponent = ComponentManager.Instance.MediaTypeComponent;
            mediaTypesComboBox.SelectedItem = mediaComponent.Get(_dataView.SelectedEdition.Entity.MediaTypeId).Name;
            editionGrid.Visibility = Visibility.Visible;
            manageEditionPanel.Visibility = Visibility.Collapsed;
            applyEditionChangesButton.Content = "Edit";
            SetBindingForQuantityTextBox();
        }

        private bool ValidateMovieInput()
        {
            return (titleTextBox.Validate() &&
                imdbRatingTextBox.Validate() &&
                webPageTextBox.Validate());
        }


        private void applyMovieChangesButton_Click(object sender, RoutedEventArgs e)
        {
            if (!ValidateMovieInput())
                return;
            ComponentManager.Instance.MovieComponent.AddOrUpdate(_dataView.Movie.Entity);
            _dataView.IsReadOnly = true;
        }

        private void cancelMovieChangesButton_Click(object sender, RoutedEventArgs e)
        {
            _dataView.IsReadOnly = true;
            _dataView.Movie = new Movie(ComponentManager.Instance.MovieComponent.Get(_dataView.Movie.Entity.Id));
        }

        private bool ValidateEdition()
        {
            return (publisherTextBox.Validate() &&
                priceTextBox.Validate() &&
                quantityTextBox.Validate());
        }

        private void applyEditionChangesButton_Click(object sender, RoutedEventArgs e)
        {
            if (!ValidateEdition())
                return;
            ComponentManager.Instance.EditionComponent.AddOrUpdate(_dataView.SelectedEdition.Entity);
            manageEditionPanel.Visibility = Visibility.Visible;
            editionGrid.Visibility = Visibility.Collapsed;
        }

        private void cancelEditionChangesButton_Click(object sender, RoutedEventArgs e)
        {
            manageEditionPanel.Visibility = Visibility.Visible;
            editionGrid.Visibility = Visibility.Collapsed;
        }

        private bool ValidateDiscount()
        {
            return (discountValueTextBox.Validate() && validUntilDatePicker.Validate());
        }

        private void applyDiscountButton_Click(object sender, RoutedEventArgs e)
        {
            if (!ValidateDiscount())
                return;
            var component = ComponentManager.Instance.TemporaryDiscountComponent;
            component.SetDiscount(_dataView.SelectedEdition.Entity, _dataView.DiscountValue, _dataView.DiscountValidUntil);
            manageEditionPanel.Visibility = Visibility.Visible;
            manageDiscountGrid.Visibility = Visibility.Collapsed;
        }

        private void cancelDiscountButton_Click(object sender, RoutedEventArgs e)
        {
            manageEditionPanel.Visibility = Visibility.Visible;
            manageDiscountGrid.Visibility = Visibility.Collapsed;
        }

        private void defaultDiscountButton_Click(object sender, RoutedEventArgs e)
        {
            _dataView.DiscountValue = 0;
            _dataView.DiscountValidUntil = DateTime.Today;
        }

        private void addToCartButton_Click(object sender, RoutedEventArgs e)
        {
            var cart = (App.Current as App).CartDataView.CurrentCart.Entity;
            var globalResources = (Application.Current as App).Resources;
            try
            {
                ComponentManager.Instance.LoanCartComponent.AddEditionToCart(cart, _dataView.SelectedEdition.Entity);
            }
            catch (ItemDuplicateException<Guid>)
            {
                string message = string.Format((string)globalResources["addToCartFailedMessage"], _dataView.SelectedEdition.MovieTitle);
                MessageBox.Show(message, "The edition is already in the cart.", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (NotEnoughException)
            {
                string message = string.Format((string)globalResources["zeroInStockMessage"], _dataView.SelectedEdition.MovieTitle);
                MessageBox.Show(message, "Nothing in stock.", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void dashboardButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	NavigationService.Navigate(new Dashboard());
        }

        private void customersButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	NavigationService.Navigate(new Customers());
        }

        private void moviesButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	NavigationService.Navigate(new Movies());
        }

        private void statisticsButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	NavigationService.Navigate(new Statistics());
        }

        private void deleteMovieButton_Click(object sender, RoutedEventArgs e)
        {
            Movie movie = _dataView.Movie;
            var globalResources = (Application.Current as App).Resources;
            if (!ComponentManager.Instance.MovieComponent.CanDelete(movie.Entity))
            {
                string message = string.Format((string)globalResources["deleteMovieFailedMessage"], movie.Entity.Title, movie.NotReturnedLoansCount);
                MessageBox.Show(message, "Can't delete movie.", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            var result = MessageBox.Show("Do you really want do delete this movie?", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
                ComponentManager.Instance.MovieComponent.Delete(movie.Entity);
            NavigationService.GoBack();
        }


   
                   


	}
}